import 'package:flutter/material.dart';
import '../core/gitcode_api.dart';

/// 自定义仓库列表卡片组件
/// 封装了仓库信息的展示，包括名称、描述、统计信息等
class RepositoryCard extends StatelessWidget {
  const RepositoryCard({
    super.key,
    required this.repository,
    this.onTap,
    this.height,
  });

  final GitCodeRepository repository;
  final VoidCallback? onTap;
  /// 卡片固定高度，默认为 200
  final double? height;
  
  // 固定每行的高度常量
  static const double _titleRowHeight = 28.0;      // 仓库名称行高度
  static const double _descriptionRowHeight = 48.0; // 描述行高度（2行）
  static const double _statsRowHeight = 24.0;      // 统计信息行高度
  static const double _updateTimeRowHeight = 20.0; // 更新时间行高度
  static const double _spacing = 12.0;              // 行间距
  static const double _smallSpacing = 8.0;          // 小间距
  static const double _padding = 16.0;              // 内边距

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final muted = theme.colorScheme.onSurfaceVariant;
    // 计算实际需要的高度：padding(上下) + 标题 + 间距 + 描述 + 间距 + 统计 + 小间距 + 更新时间
    // 增加16px余量以防止溢出
    final calculatedHeight = _padding * 2 + 
        _titleRowHeight + 
        _spacing + 
        _descriptionRowHeight + 
        _spacing + 
        _statsRowHeight + 
        _smallSpacing + 
        _updateTimeRowHeight +
        16.0; // 额外余量防止溢出
    final cardHeight = height ?? calculatedHeight;

    return SizedBox(
      height: cardHeight,
      child: Card(
        elevation: 2,
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        child: InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(12),
          child: Padding(
            padding: const EdgeInsets.all(_padding),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // 第1行：仓库名称和图标（固定高度）
                SizedBox(
                  height: _titleRowHeight,
                  child: Row(
                    children: [
                      Icon(
                        repository.isPrivate == true
                            ? Icons.lock_outline
                            : Icons.folder_outlined,
                        color: theme.colorScheme.primary,
                        size: 20,
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          repository.fullName,
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: _spacing),
                // 第2行：描述（固定高度，即使没有描述也保留空间）
                SizedBox(
                  height: _descriptionRowHeight,
                  child: repository.description?.isNotEmpty == true
                      ? Text(
                          repository.description!,
                          style: theme.textTheme.bodyMedium?.copyWith(
                            color: muted,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        )
                      : const SizedBox.shrink(),
                ),
                const SizedBox(height: _spacing),
                // 第3行：统计信息（固定高度，使用Row确保不换行）
                SizedBox(
                  height: _statsRowHeight,
                  child: Row(
                    children: [
                      if (repository.language != null) ...[
                        _buildStatItem(
                          icon: Icons.code,
                          label: repository.language!,
                          color: _getLanguageColor(repository.language!),
                          muted: muted,
                        ),
                        const SizedBox(width: 16),
                      ],
                      _buildStatItem(
                        icon: Icons.star_outline,
                        label: _formatNumber(repository.stars ?? 0),
                        muted: muted,
                      ),
                      const SizedBox(width: 16),
                      _buildStatItem(
                        icon: Icons.call_split,
                        label: _formatNumber(repository.forks ?? 0),
                        muted: muted,
                      ),
                      const Spacer(), // 填充剩余空间
                    ],
                  ),
                ),
                const SizedBox(height: _smallSpacing),
                // 第4行：更新时间（固定高度，即使没有更新时间也保留空间）
                SizedBox(
                  height: _updateTimeRowHeight,
                  child: repository.updatedAt != null
                      ? Text(
                          '更新于 ${repository.updatedAt}',
                          style: theme.textTheme.bodySmall?.copyWith(
                            color: muted,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        )
                      : const SizedBox.shrink(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildStatItem({
    required IconData icon,
    required String label,
    Color? color,
    required Color muted,
  }) {
    final effectiveColor = color ?? muted;

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 16, color: effectiveColor),
        const SizedBox(width: 4),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: effectiveColor,
          ),
        ),
      ],
    );
  }

  Color _getLanguageColor(String language) {
    // 根据语言返回不同颜色
    final colors = <String, Color>{
      'Dart': Colors.blue,
      'Java': Colors.orange,
      'JavaScript': Colors.yellow[700]!,
      'Python': Colors.blue[300]!,
      'Go': Colors.cyan,
      'TypeScript': Colors.blue[800]!,
      'C++': Colors.pink,
      'C': Colors.grey[800]!,
      'Swift': Colors.orange[300]!,
      'Kotlin': Colors.purple,
      'Rust': Colors.orange[900]!,
    };
    return colors[language] ?? Colors.grey[600]!;
  }

  String _formatNumber(int number) {
    if (number >= 1000) {
      return '${(number / 1000).toStringAsFixed(1)}k';
    }
    return number.toString();
  }
}

